package com.ruoyi.answer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.answer.domain.ExamComposition;
import com.ruoyi.answer.domain.ExamPaperQuestion;
import com.ruoyi.answer.domain.ExamQuestionChoice;
import com.ruoyi.answer.domain.excel.ExcelPaper;
import com.ruoyi.answer.domain.vo.ExamCompositionVo;
import com.ruoyi.answer.domain.vo.ExamPaperQuestionVo;
import com.ruoyi.answer.domain.vo.ExamQuestionChoiceVo;
import com.ruoyi.answer.mapper.ExamCompositionMapper;
import com.ruoyi.answer.mapper.ExamPaperQuestionMapper;
import com.ruoyi.answer.mapper.ExamQuestionChoiceMapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.edu.domain.EduTeacher;
import com.ruoyi.edu.domain.vo.EduCourseVo;
import com.ruoyi.edu.domain.vo.EduTeacherVo;
import com.ruoyi.edu.mapper.EduCourseMapper;
import com.ruoyi.edu.mapper.EduTeacherMapper;
import com.ruoyi.system.mapper.SysOssMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.answer.domain.bo.ExamPaperBo;
import com.ruoyi.answer.domain.vo.ExamPaperVo;
import com.ruoyi.answer.domain.ExamPaper;
import com.ruoyi.answer.mapper.ExamPaperMapper;
import com.ruoyi.answer.service.IExamPaperService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 试卷管理Service业务层处理
 *
 * @author kun_er
 * @date 2022-08-16
 */
@RequiredArgsConstructor
@Service
public class ExamPaperServiceImpl implements IExamPaperService {

    private final ExamPaperMapper baseMapper;

    private final ExamCompositionMapper examCompositionMapper;
    private final ExamPaperQuestionMapper examPaperQuestionMapper;
    private  final SysOssMapper sysOssMapper;
    private final ExamQuestionChoiceMapper examQuestionChoiceMapper;
    private final EduCourseMapper eduCourseMapper;
    private final EduTeacherMapper eduTeacherMapper;

    /**
     * 查询试卷管理
     */
    @Override
    public ExamPaperVo queryById(Long id){
        ExamPaperVo examPaperVo = baseMapper.selectVoById(id);
        if (examPaperVo.getTrainingId()!=null){
            EduCourseVo eduCourseVo = eduCourseMapper.selectVoById(examPaperVo.getTrainingId());
            examPaperVo.setTitle(eduCourseVo.getTitle());
        }
        if (examPaperVo.getMarkingAccount()!=null){
            EduTeacherVo eduTeacherVo = eduTeacherMapper.selectVoById(examPaperVo.getMarkingAccount());
            examPaperVo.setName(eduTeacherVo.getName());
        }

        return examPaperVo;
    }

    /**
     * 查询试卷管理列表
     */
    @Override
    public TableDataInfo<ExamPaperVo> queryPageList(ExamPaperBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ExamPaper> lqw = buildQueryWrapper(bo);
        Page<ExamPaperVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<ExamPaperVo> records = result.getRecords();
        List<ExamPaperVo> collect = records.stream().map(item -> {
            if (item.getTrainingId()!=null) {
                EduCourseVo eduCourseVo = eduCourseMapper.selectVoById(item.getTrainingId());
                if (eduCourseVo != null) {
                    item.setTitle(eduCourseVo.getTitle());
                }
            }
            if (item.getMarkingAccount()!=null) {
                EduTeacherVo eduTeacherVo = eduTeacherMapper.selectVoById(item.getMarkingAccount());
                if (eduTeacherVo != null) {
                    item.setName(eduTeacherVo.getName());
                }
            }
            return item;
        }).collect(Collectors.toList());
        result.setRecords(collect);
        return TableDataInfo.build(result);
    }

    /**
     * 查询试卷管理列表
     */
    @Override
    public List<ExamPaperVo> queryList(ExamPaperBo bo) {
        LambdaQueryWrapper<ExamPaper> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ExamPaper> buildQueryWrapper(ExamPaperBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ExamPaper> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTrainingId() != null, ExamPaper::getTrainingId, bo.getTrainingId());
        lqw.eq(StringUtils.isNotBlank(bo.getPaperType()), ExamPaper::getPaperType, bo.getPaperType());
        lqw.like(StringUtils.isNotBlank(bo.getPaperName()), ExamPaper::getPaperName, bo.getPaperName());
        lqw.eq(bo.getState() != null, ExamPaper::getState, bo.getState());
        return lqw;
    }

    /**
     * 新增试卷管理
     */
    @Override
    public Boolean insertByBo(ExamPaperBo bo) {
        ExamPaper add = BeanUtil.toBean(bo, ExamPaper.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改试卷管理
     */
    @Override
    public Boolean updateByBo(ExamPaperBo bo) {
        ExamPaper update = BeanUtil.toBean(bo, ExamPaper.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ExamPaper entity){

        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除试卷管理
     */
    @Transactional
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            for (Long id:ids){
                ExamPaperVo examPaperVo = baseMapper.selectVoById(id);
                List<ExamComposition> list = examCompositionMapper.selectList(new QueryWrapper<ExamComposition>().eq("paper_id", id));
                for (ExamComposition examComposition:list){
                    examPaperQuestionMapper.deleteById(examComposition.getQuestionId());
                    examQuestionChoiceMapper.delete(new QueryWrapper<ExamQuestionChoice>().eq("question_id",examComposition.getQuestionId()));
                }


                baseMapper.deleteById(id);
                examCompositionMapper.delete(new QueryWrapper<ExamComposition>().eq("paper_id",id));

            }
        }
        return true;
    }

    /**
     * 导入Excel试卷
     * @param list
     * @param name
     * @return
     */
    @Transactional
    @Override
    public R importCustomer(List<ExcelPaper> list,String name) {
        ExamPaper examPaper = new ExamPaper();
        String[] split = name.split("\\.");
        Long count = baseMapper.selectCount(new QueryWrapper<ExamPaper>().eq("paper_name", split[0]).eq("del_flag",0));
        if (count>0){
            return R.fail("试卷已存在");
        }
        examPaper.setState(1L);
        examPaper.setPaperName(split[0]);
        int insert = baseMapper.insert(examPaper);
        if (insert>0){
            for (int i = 0; i < list.size(); i++) {
                ExamComposition examComposition = new ExamComposition();
                ExamPaperQuestion examPaperQuestion = new ExamPaperQuestion();
                BeanUtils.copyProperties(list.get(i),examComposition);
                BeanUtils.copyProperties(list.get(i),examPaperQuestion);
                int i2 = examPaperQuestionMapper.insert(examPaperQuestion);
                examComposition.setPaperId(examPaper.getId());
                examComposition.setQuestionId(examPaperQuestion.getId());
                int i1 = examCompositionMapper.insert(examComposition);
                List<String> choices = new ArrayList<>();
                choices.add(list.get(i).getChoiceA());
                choices.add(list.get(i).getChoiceB());
                choices.add(list.get(i).getChoiceC());
                choices.add(list.get(i).getChoiceD());


                String[] c=new String[] {"A","B","C","D"};
                for (int j = 0; j < choices.size(); j++) {
                    ExamQuestionChoice examQuestionChoice = new ExamQuestionChoice();
                    examQuestionChoice.setQuestionId(examPaperQuestion.getId());
                    examQuestionChoice.setChoiceName(c[j]);
                    examQuestionChoice.setChoiceTitle(choices.get(j));
                    examQuestionChoiceMapper.insert(examQuestionChoice);

                }
            }
        }
        return R.ok("导入试卷成功");
    }
}
